#!/usr/bin/env python

import os
import optparse
import sys
import subprocess
import tempfile

from charmicat import BadCommandLineError

from ypipi.slurm import BASFSlurmScript

def main():
    '''
    mumupi0pi0_job_scripts.py [opts] BASF_module_name input_file [input_file [...]]

    Submits one job running `module_name' per `input_file' using `sbatch'.
    '''
    
    op = optparse.OptionParser(usage=main.__doc__)
    

    op.add_option("-b", "--basf", dest='basf_path', default=None,
                  help='Use BASF script at PATH in job script',
                  metavar='PATH')
    op.add_option("-j", "--job-name", dest='job_name', default=None,
                  help='Name jobs NAME in SLURM queue', 
                  metavar='NAME')
    op.add_option("-o", "--outdir", dest='outdir', default=None,
                  help='Leave output files in DIR', metavar='DIR')
    op.add_option("-t", "--duration", dest='duration', 
                  default='08:00:00', help='Set job duration of N minutes or HH:MM:SS',
                  metavar='N (or) HH:MM:SS')
    op.add_option("--nodes", dest='nnodes', type='int', default=1,
                  help='Use N nodes per job', metavar='N')
    op.add_option('-m', '--module-path', dest='module_path', default=None,
                  help='Add PATH to the LD_LIBRARY_PATH for the job',
                  metavar='PATH')
    op.add_option("--stdout", dest='stdout', default=None,
                  help='Redirect job stdout to PATH', metavar='PATH')
    op.add_option("--stderr", dest='stderr', default=None,
                  help='Redirect job stderr to PATH', metavar='PATH')
    op.add_option("--stdout-dir", dest='stdoutdir', default=None,
                  help='Place job stdout in DIR', metavar='DIR')
    op.add_option("--stderr-dir", dest='stderrdir', default=None,
                  help='Place job stderr in DIR', metavar='DIR')

    opts, args = op.parse_args()

    if len(args) == 0:
        msg = "Please supply the BASF module name and at least one input file."
        raise BadCommandLineError(msg, -1)


    module_name = args.pop(0)

    if len(args) == 0:
        msg = "Please supply at least one input file."
        raise BadCommandLineError(msg, -2)
    
    for i, path in enumerate(args):
        sys.stdout.write("{0}/{1} scripts written\r".format(i, len(args)))
        sys.stdout.flush()

        scr = BASFSlurmScript(module_name, path, **vars(opts))

        script_path = os.path.basename(path) + '.1x.sh'
        with open(script_path, 'w') as fp:
            fp.write(str(scr))
    
    print "{0}/{0} scripts written\r".format(len(args))

    return 0



if __name__ == "__main__":
    try:
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
